//
//  WBNetworkManager.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/3.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}

// 网络管理工具
class WBNetworkManager: AFHTTPSessionManager {
    
    static let shared: WBNetworkManager = {
        let instance = WBNetworkManager()

        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()
    
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    /// 专门负责拼接token的网络请求
    ///
    /// - parameter method:     请求方式
    /// - parameter URLString:  URL
    /// - parameter parameters: 参数
    /// - parameter name:       上传文件使用的字段名
    /// - parameter data:       上传的二进制数据
    /// - parameter completion: 回调闭包
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String:Any]?, name:String? = nil, data: Data? = nil, completion:@escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        
        guard let token = userAccount.access_token else {
            completion(nil, false)
            debugPrint("没有token，需要登录")
            
            return
        }
        
        var parameters = parameters
        
        if parameters == nil {
            parameters = [String:Any]()
        }
        
        parameters!["access_token"] = token
        
        if let name = name, let data = data {
            upload(urlString: URLString, parameters: parameters, name: name, data: data, completion: completion)
        }else{
            request(method: method, URLString: URLString, parameters: parameters, completion: completion)
        }
    }
    
    /// 封装AFN的上传文件方法
    /// 必须是POST
    ///
    /// - parameter urlString:  URL
    /// - parameter parameters: 参数字典
    /// - parameter name:       接收上传数据的服务器字段
    /// - parameter data:       上传的二进制数据
    /// - parameter completion: 回调闭包
    func upload(urlString: String, parameters: [String:Any]?, name: String, data: Data, completion: @escaping (Any, Bool)->()) {
        
        post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
            
            formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            }, progress: nil, success: { (_, json) in
                completion(json, true)
            }) { (_, error) in
                debugPrint(error)
        }
    }
    
    /// 使用一个函数封装AFN的GET和POST请求
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String:Any]?, completion:@escaping (_ json: Any?, _ isSuccess: Bool) -> ()){
        
        let success = {(task: URLSessionDataTask, json: Any?) in
            completion(json, true)
        }
        
        let failure = {(task: URLSessionDataTask?, error: Error) in
            debugPrint("网络请求错误 \(error)")
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                debugPrint("token过期了")
            }
            
            completion(error, false) 
        }
        
        switch method {
        case .GET:
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            break
        case .POST:
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        
    }
}
